package baibeiwallet.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alm.token.GlideApp;
import com.alm.token.MyApp;
import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.data.bean.CoinDetailData;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;
import com.alm.token.utils.LogUtil;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yzq.zxinglibrary.android.CaptureActivity;

import org.web3j.crypto.CipherException;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.Keys;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.tx.Transfer;
import org.web3j.utils.Convert;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;

import baibeiwallet.BaibeiWallet;
import baibeiwallet.Constant;
import baibeiwallet.WalletManager;
import baibeiwallet.WalletUtils;
import baibeiwallet.model.TokenModel;
import baibeiwallet.solidity.Token;
import baibeiwallet.utils.BaibeiTransferUtils;
import baibeiwallet.utils.DialogUtils;
import baibeiwallet.utils.Web3jUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

//import com.alm.token.ui.activity.QRCodeScannerActivity;
//import com.yzq.zxinglibrary.android.CaptureActivity;
//import com.uuzuche.lib_zxing.activity.CaptureActivity;
//import com.uuzuche.lib_zxing.activity.CodeUtils;
//import com.uuzuche.lib_zxing.activity.ZXingLibrary;

public class TransferActivity1 extends BaseActivity {
    public static int REQ_SCAN_CODE = 100;
    public static String TAG = TransferActivity1.class.getSimpleName();
    @BindView(R.id.leftItem)
    ImageView leftItem;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_balance_token)
    TextView mTvBalanceToken;
    @BindView(R.id.et_amount_transfer)
    EditText mEtAmount;
    @BindView(R.id.et_address_other)
    EditText mEtAddress;
    @BindView(R.id.tv_transfer_address_one)
    TextView mTvAddressTransferFrom;
    @BindView(R.id.tv_balance_one)
    TextView mTvBalanceFrom;
    @BindView(R.id.tv_transfer_address_two)
    TextView mTvAddressTransferTo;
    @BindView(R.id.tv_balance_two)
    TextView mTvBalanceTo;
    @BindView(R.id.tv_transfer_data)
    TextView mTvTransferData;
    @BindView(R.id.tv_transfer_gase)
    TextView mTvTransferGase;
    @BindView(R.id.tv_bizhongshow)
    TextView mTvBizhongshow;

    BaibeiWallet mWallet;
    Token mContract;
    TokenModel mTokenModel;
    @BindView(R.id.img_more)
    ImageView imgMore;
    @BindView(R.id.img_bizhongicon)
    ImageView imgbizhongicon;

    @BindView(R.id.ly_ooutmoneybizhongtop)
    RelativeLayout lyOutmoneybizhongtop;


    private BigInteger gasebigInteger = new BigInteger("100000000000");
    private BigDecimal gaselimitbigInteger = new BigDecimal("600000");

    @Override
    protected MyPreenter initPreenter() {
        return null;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_transfer33;
    }

    @Override
    protected void initVariables() {
        new ActionBarHelper(this).setTitle(getString(R.string.title_hint_item21));

        int index = getIntent().getIntExtra("index", 0);
        mTokenModel = getIntent().getParcelableExtra("token");
        String result = getIntent().getStringExtra("adress");


        //设置EditText的显示方式为多行文本输入
        mEtAddress.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        //文本显示的位置在EditText的最上方
        mEtAddress.setGravity(Gravity.CENTER_VERTICAL);
        mEtAddress.setText("");
        //改变默认的单行模式
        mEtAddress.setSingleLine(false);
        //水平滚动设置为False
        mEtAddress.setHorizontallyScrolling(false);

        if (!TextUtils.isEmpty(result)) {
            mEtAddress.setText(result);
            mEtAddress.setSelection(mEtAddress.getText().length());
        }

        mWallet = WalletManager.getInstance().getWallet(index);


        if (mTokenModel == null) {
            return;
        }
        mTvTitle.setText(mTokenModel.getTitle());
        mTvBizhongshow.setText(mTokenModel.getTitle());
        imgMore.setVisibility(View.GONE);
        for (CoinDetailData.DataBean dataBean : MyApp.coinDetailDataBean) {
            if (dataBean != null && dataBean.getWallet() != null && dataBean.getWallet().getName().indexOf(mTokenModel.getTitle()) != -1) {
                GlideApp.with(TransferActivity1.this).load(dataBean.getWallet().getLogo())
                        .listener(new RequestListener<Drawable>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
//                                if (EmptyUtils.isNotEmpty(resource)) {
//                                    CommonUtil. changeSVGColor(TransferActivity1.this, imgbizhongicon, resource, R.color.black);
//                                    return true;
//                                }
                                return false;
                            }
                        })
                        .error(R.drawable.icon_arctic).into(imgbizhongicon);
                break;
            }
        }

        if (getIntent().getIntExtra("type", 0) == 1) {////提取过来
            mTvTitle.setText("ETH");
            mTvBizhongshow.setText("ETH");
            for (CoinDetailData.DataBean dataBean : MyApp.coinDetailDataBean) {
                if (dataBean != null && dataBean.getWallet() != null && dataBean.getWallet().getName().indexOf("ETH") != -1) {
                    GlideApp.with(TransferActivity1.this).load(dataBean.getWallet().getLogo())
                            .listener(new RequestListener<Drawable>() {
                                @Override
                                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                    return false;
                                }

                                @Override
                                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
//                                    if (EmptyUtils.isNotEmpty(resource)) {
//                                        CommonUtil. changeSVGColor(TransferActivity1.this, imgbizhongicon, resource, R.color.black);
//                                        return true;
//                                    }
                                    return false;
                                }
                            })
                            .error(R.drawable.icon_arctic).into(imgbizhongicon);
                    break;
                }
            }
            imgMore.setVisibility(View.VISIBLE);
            lyOutmoneybizhongtop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showPopupMenu2(lyOutmoneybizhongtop);
                }
            });

        }


        if (mTokenModel.isEth) {
            getBalanceForETH(Keys.toChecksumAddress(mWallet.getWalletFile().getAddress()));
        } else {
            loadContract();
        }
        getGasForETH();//获取gasprice

        BigDecimal bigDecimal1 = new BigDecimal("1000000000000000000.00000");
        BigDecimal bigDecimal2=BigDecimal.valueOf(0.0005);
        gaselimitbigInteger = bigDecimal2.multiply(bigDecimal1).divide(new BigDecimal(gasebigInteger), BigDecimal.ROUND_HALF_UP);
        LogUtil.e("gasebigInteger="+gasebigInteger);
        LogUtil.e("gaselimitbigInteger="+gaselimitbigInteger);
        mTvTransferGase.setText("0.0005"  + " ETH");
    }

    public void showPopupMenu2(View view) {
        //参数View 是设置当前菜单显示的相对于View组件位置，具体位置系统会处理
        PopupMenu popupMenu = new PopupMenu(this, view);
        //加载menu布局
        Menu menu = popupMenu.getMenu();
        menu.add("ETH");
        menu.add(Constant.G12ContractName);
        popupMenu.getMenuInflater().inflate(R.menu.menu_popmenu, menu);


        //设置menu中的item点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {

                if (item.getTitle().toString().indexOf("ETH") != -1 && !mTokenModel.isEth) {
                    mTvTitle.setText("ETH");
                    mTvBizhongshow.setText("ETH");
                    for (CoinDetailData.DataBean dataBean : MyApp.coinDetailDataBean) {
                        if (dataBean != null && dataBean.getWallet() != null && dataBean.getWallet().getName().indexOf("ETH") != -1) {
                            GlideApp.with(TransferActivity1.this).load(dataBean.getWallet().getLogo())
                                    .listener(new RequestListener<Drawable>() {
                                        @Override
                                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                            return false;
                                        }

                                        @Override
                                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
//                                            if (EmptyUtils.isNotEmpty(resource)) {
//                                                CommonUtil. changeSVGColor(TransferActivity1.this, imgbizhongicon, resource, R.color.black);
//                                                return true;
//                                            }
                                            return false;
                                        }
                                    })
                                    .error(R.drawable.icon_arctic).into(imgbizhongicon);
                            break;
                        }
                    }
                    mTokenModel = new TokenModel("", "ETH", true);
                    getBalanceForETH(Keys.toChecksumAddress(mWallet.getWalletFile().getAddress()));
                } else if (item.getTitle().toString().indexOf(Constant.G12ContractName) != -1 && mTokenModel.isEth) {
                    mTvTitle.setText(Constant.G12ContractName + "");
                    mTvBizhongshow.setText(Constant.G12ContractName + "");
                    for (CoinDetailData.DataBean dataBean : MyApp.coinDetailDataBean) {
                        if (dataBean != null && dataBean.getWallet() != null && dataBean.getWallet().getName().indexOf(Constant.G12ContractName) != -1) {
                            GlideApp.with(TransferActivity1.this).load(dataBean.getWallet().getLogo())
                                    .listener(new RequestListener<Drawable>() {
                                        @Override
                                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                            return false;
                                        }

                                        @Override
                                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
//                                            if (EmptyUtils.isNotEmpty(resource)) {
//                                                CommonUtil. changeSVGColor(TransferActivity1.this, imgbizhongicon, resource, R.color.black);
//                                                return true;
//                                            }
                                            return false;
                                        }
                                    })
                                    .error(R.drawable.icon_arctic).into(imgbizhongicon);
                            break;
                        }
                    }
                    mTokenModel = new TokenModel(Constant.G12ContractAddress, Constant.G12ContractName, false);
                    loadContract();
                }

                return true;
            }
        });
        popupMenu.show();
    }

    @Override
    protected void initViews() {
        mEtAmount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 4) {
                        s = s.toString().subSequence(0, s.toString().indexOf(".") + 5);
                        mEtAmount.setText(s);
                        mEtAmount.setSelection(s.length());
                    }
                }
                if (s.toString().trim().substring(0).equals(".")) {
                    s = "0" + s;
                    mEtAmount.setText(s);
                    mEtAmount.setSelection(2);
                }

                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        mEtAmount.setText(s.subSequence(0, 1));
                        mEtAmount.setSelection(1);
                        return;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void loadData() {

    }

    @OnClick(R.id.btn_qrcode_address)
    public void onClickQrcodeAddress() {
        //扫码
        RxPermissions rxPermissions = new RxPermissions(TransferActivity1.this);
        rxPermissions.request(Manifest.permission.CAMERA)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Boolean granted) {
                        if (granted) {
                            if (!CommonUtil.isCameraOpen()) {
//                                ZXingLibrary.initDisplayOpinion(getApplicationContext());
////                                Intent intent = new Intent(TransferActivity1.this, CaptureActivity.class);
//                                Intent intent = new Intent(TransferActivity1.this, QRCodeScannerActivity.class);
//                                startActivityForResult(intent, REQ_SCAN_CODE);

                                Intent intent = new Intent(TransferActivity1.this, CaptureActivity.class);
                                intent.putExtra(com.yzq.zxinglibrary.common.Constant.INTENT_ZXING_CONFIG, MyApp.getZxingConfig());
                                startActivityForResult(intent, REQ_SCAN_CODE);


                            } else {
                                Toast.makeText(TransferActivity1.this, getString(R.string.profile_hint_item1), Toast.LENGTH_SHORT).show();
//                                    showToast("该相机目前正在被另一个应用程序打开。请关闭其他应用程序，然后再试一次。");
                            }
                        } else {
                            Toast.makeText(TransferActivity1.this, getString(R.string.profile_hint_item2), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_SCAN_CODE && resultCode == RESULT_OK&& data != null  ) {
                String result =   data.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT);
//            String result =null;//   data.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT);
                Log.i("TAG", "扫描结果:" + result);
                if (!TextUtils.isEmpty(result)) {
                    mEtAddress.setText(result);
                    mEtAddress.setSelection(mEtAddress.getText().length());
                } else {
                    showToast(getString(R.string.profile_hint_item3));
//                    Toast.makeText(this, "结果为空！", Toast.LENGTH_SHORT).show();
                }

        }else   {
//            showToast(getString(R.string.profile_hint_item4));
//                Toast.makeText(this, "解析二维码失败", Toast.LENGTH_SHORT).show();
//                AppUI.success(getContext(), "解析二维码失败");
        }
    }

    @OnClick(R.id.btn_transfer)
    public void onClickTransfer() {
        if (mWallet == null) {
            Toast.makeText(this, getString(R.string.profile_hint_item6), Toast.LENGTH_SHORT).show();
            return;
        }

        String amount = mEtAmount.getText().toString();
        String addr = mEtAddress.getText().toString();
        if (TextUtils.isEmpty(amount)) {
            Toast.makeText(this, getString(R.string.profile_hint_item27), Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(addr)) {
            Toast.makeText(this, getString(R.string.profile_hint_item28), Toast.LENGTH_SHORT).show();
            return;
        }

        DialogUtils.enterPwd(this, (pwd) -> {
            Credentials c = null;
            try {
                c = WalletUtils.loadCredentials(pwd, mWallet.getWalletFile());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (CipherException e) {
                Toast.makeText(this, getString(R.string.profile_hint_item29), Toast.LENGTH_SHORT).show();
                e.printStackTrace();
            }
            sendTransaction(c, addr, Double.valueOf(amount));
        });
    }

    private void sendTransaction(Credentials c, String toAddress, double value) {
        if (mTokenModel.isEth) {
            sendTransactionForETH(c, toAddress, value);
        } else {
            sendTransactionForOther(c, toAddress, value);
        }
    }

    private void sendTransactionForETH(Credentials c, String toAddress, double value) {
        Log.i("TAG", "onClickTransfer: value = " + BigDecimal.valueOf(value));
        showWaitDialog();
        Web3j web3j = Web3jUtils.initWeb3j(null);
        Single.fromCallable(() -> Transfer.sendFunds(
                web3j, c, toAddress,
                BigDecimal.valueOf(value), Convert.Unit.ETHER)
                .send())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<TransactionReceipt>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        LogUtil.d("onSubscribe: Disposable1");


                    }

                    @Override
                    public void onSuccess(TransactionReceipt transactionReceipt) {
                        hideWaitDialog();
                        Log.i("TAG", "onSuccess:  " + transactionReceipt.toString());
                        Toast.makeText(TransferActivity1.this, getString(R.string.profile_hint_item30), Toast.LENGTH_SHORT).show();
                        mTvTransferData.setText(transactionReceipt.toString());
                        String fromAddr = mWallet.getWalletFile().getAddress();
                        getBalance(Keys.toChecksumAddress(fromAddr), mTvAddressTransferFrom, mTvBalanceFrom);
                        getBalance(Keys.toChecksumAddress(toAddress), mTvAddressTransferTo, mTvBalanceTo);
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        if (e.toString().indexOf("insufficient funds for gas * price + value") != -1) {
                            Toast.makeText(TransferActivity1.this, getString(R.string.profile_hint_item31), Toast.LENGTH_SHORT).show();
                        } else
                            Toast.makeText(TransferActivity1.this, getString(R.string.profile_hint_item32), Toast.LENGTH_SHORT).show();
                        LogUtil.d("onError: " + e.toString());
                        e.printStackTrace();
                    }
                });
    }


    private void sendTransactionForOther(Credentials c, String toAddr, double value) {
        Log.i(TAG, "transferByContract:转账金额为 " + value);
        showWaitDialog();
        Single.fromCallable(() -> mContract.transfer(toAddr, BigDecimal.valueOf(value).toBigInteger())
                .send())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SingleObserver<TransactionReceipt>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onSuccess(TransactionReceipt transactionReceipt) {
                        hideWaitDialog();
                        Log.i(TAG, "onSuccess: 挖矿成功！" + transactionReceipt.toString());
                        Toast.makeText(TransferActivity1.this, getString(R.string.profile_hint_item30), Toast.LENGTH_SHORT).show();
                        mTvTransferData.setText(transactionReceipt.toString());
                        String fromAddr = mWallet.getWalletFile().getAddress();
                        getBalance(Keys.toChecksumAddress(fromAddr), mTvAddressTransferFrom, mTvBalanceFrom);
                        getBalance(Keys.toChecksumAddress(toAddr), mTvAddressTransferTo, mTvBalanceTo);
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideWaitDialog();
                        LogUtil.d("onError: 挖矿失败 " + e.toString());
                        if (e.toString().indexOf("insufficient funds for gas * price + value") != -1) {
                            Toast.makeText(TransferActivity1.this, getString(R.string.profile_hint_item31), Toast.LENGTH_SHORT).show();
                        } else
                            Toast.makeText(TransferActivity1.this, getString(R.string.profile_hint_item32), Toast.LENGTH_SHORT).show();
                        e.printStackTrace();
                    }
                });
    }


    public Single<BigInteger> getBalance(String address) {
        if (mTokenModel.isEth) {
            return BaibeiTransferUtils.getBalanceForETH(address);
        } else {
            return BaibeiTransferUtils.balanceOf(mContract, address);
        }
    }

    private void getBalanceForETH(String addr) {
        BaibeiTransferUtils.getBalanceForETH(addr)
                .subscribe(mBalanceObserver);
    }

    private void getGasForETH() {
        BaibeiTransferUtils.getGasForETH()
                .subscribe(mGasObserver);
    }


    private void getBalance(String add, TextView tvAddr, TextView tvBal) {
        getBalance(add)
                .subscribe(new SingleObserver<BigInteger>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onSuccess(BigInteger bigInteger) {
                        Log.i("TAG", "onClickGetBalance: " + bigInteger);
                        tvAddr.setText(add);
                        tvBal.setText("" + bigInteger.toString());
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtil.d("onClickGetBalance: 报错了 ");
                        tvAddr.setText("err: " + e.getMessage());
                        tvBal.setText("");
                        e.printStackTrace();
                    }
                });
    }

    private SingleObserver<BigInteger> mGasObserver = new SingleObserver<BigInteger>() {
        @Override
        public void onSubscribe(Disposable d) {
        }

        @Override
        public void onSuccess(BigInteger bigInteger) {
            LogUtil.d("gas=" + bigInteger.toString());
            gasebigInteger = bigInteger;

//            BigDecimal bigDecimal = new BigDecimal(gasebigInteger.multiply(getGasLimit()) + ".00000");//gaseprice*gaselimit
//            BigDecimal bigDecimal1 = new BigDecimal("1000000000000000000.00000");


            BigDecimal bigDecimal1 = new BigDecimal("1000000000000000000.00000");
            BigDecimal bigDecimal2=BigDecimal.valueOf(0.0005);
            gaselimitbigInteger = bigDecimal2.multiply(bigDecimal1).divide(new BigDecimal(gasebigInteger), BigDecimal.ROUND_HALF_UP);
            LogUtil.e("gasebigInteger="+gasebigInteger);
            LogUtil.e("gaselimitbigInteger="+gaselimitbigInteger);
            if (mTvTransferGase != null)
            mTvTransferGase.setText("0.0005" + "ETH");

//            //gaseprice*gaselimit=gasenumberprice/10^18= *ETH
//            if (mTvTransferGase != null)
//                mTvTransferGase.setText("" + bigDecimal.divide(bigDecimal1, BigDecimal.ROUND_HALF_UP) + "ETH");
        }

        @Override
        public void onError(Throwable e) {
            mTvBalanceToken.setText(getString(R.string.wallet_hint_warn6) + e.getMessage());
        }
    };

    private SingleObserver<BigInteger> mBalanceObserver = new SingleObserver<BigInteger>() {
        @Override
        public void onSubscribe(Disposable d) {
        }

        @Override
        public void onSuccess(BigInteger bigInteger) {
            if (mTokenModel != null && mTokenModel.isEth) {
                BigDecimal bigDecimal = new BigDecimal(bigInteger + ".0000");
                BigDecimal bigDecimal1 = new BigDecimal("1000000000000000000.0000");
                if (mTvBalanceToken != null)
                    mTvBalanceToken.setText(getString(R.string.currency_hint_balance, bigDecimal.divide(bigDecimal1, BigDecimal.ROUND_HALF_UP)));
            } else {
                if (mTvBalanceToken != null)
                    mTvBalanceToken.setText(getString(R.string.currency_hint_balance,bigInteger.toString()));
            }
//            mTvBalanceToken.setText("余额：" + bigInteger.toString());
        }

        @Override
        public void onError(Throwable e) {
            mTvBalanceToken.setText(getString(R.string.wallet_hint_warn6) + e.getMessage());
        }
    };

    private void getBalanceForToken() {
        if (mContract == null) {
            showToast(getString(R.string.wallet_hint_warn7));
//            Toast.makeText(this, "合约未加载完成！", Toast.LENGTH_SHORT).show();
            return;
        }

        BaibeiTransferUtils.balanceOf(mContract, mWallet.getWalletFile().getAddress())
                .subscribe(mBalanceObserver);
    }

    private void loadContract() {
        if (mTokenModel != null && mTokenModel.isEth) {
            //以太坊不需要加载合约
            return;
        }

        BaibeiTransferUtils.loadContract(mWallet, mTokenModel.getAddr(), getGasPrice(), getGasLimit())
                .subscribe(new SingleObserver<Token>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onSuccess(Token token) {
//                        Toast.makeText(TransferActivity1.this, "合约加载完成！", Toast.LENGTH_SHORT).show();
                        mContract = token;
                        getBalanceForToken();
                    }

                    @Override
                    public void onError(Throwable e) {
//                        showToast("合约加载失败!");
//                        Toast.makeText(TransferActivity1.this, "合约加载失败！", Toast.LENGTH_SHORT).show();
                        showToast(getString(R.string.common_loaderrritry));

                    }
                });
    }

    private BigInteger getGasPrice() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                Request<?, EthGasPrice> ethGasPriceRequest = Web3jUtils.initWeb3j(null).ethGasPrice();
//                BigInteger gasPrice = null;
//                try {
//
//                    EthGasPrice send = ethGasPriceRequest.send();
//                    gasPrice = send.getGasPrice();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                Log.e("9998",gasPrice.toString());
//            }
//        }).start();


//        return gasebigInteger!=null?gasebigInteger:new BigInteger("100000000000");

        return gasebigInteger;
    }

    private BigInteger getGasLimit() {

        return BigInteger.valueOf(gaselimitbigInteger.longValue());
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


}
